#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
结果格式化模块
负责教室查询结果的格式化和输出
"""

from typing import List, Dict, Any, Optional
from .building_mapper import BuildingMapper
from .room_analyzer import RoomAnalyzer


class ResultFormatter:
    """结果格式化器"""

    @staticmethod
    def format_general_result(analysis_result: Dict[str, Any],
                            building_code: str,
                            selected_weekdays: List[int],
                            selected_sections: List[int]) -> str:
        """
        格式化普通教室查询结果

        Args:
            analysis_result: 分析结果
            building_code: 教学楼代码
            selected_weekdays: 选择的星期
            selected_sections: 选择的节次

        Returns:
            格式化的结果字符串
        """
        building_name = BuildingMapper.get_building_name(building_code)
        all_rooms = analysis_result['all_rooms']
        free_rooms = analysis_result['free_rooms']

        result = f"{building_name} 空闲教室:\n\n"

        if free_rooms:
            # 按节次和星期排序，方便按节次查看
            free_rooms.sort(key=lambda x: (x['section'], x['day'], x['room']))

            # 分析连续空闲的教室
            room_sections = {}  # 教室 -> 空闲的节次列表
            for room_info in free_rooms:
                room = room_info['room']
                section = room_info['section']
                if room not in room_sections:
                    room_sections[room] = set()
                room_sections[room].add(section)

            result += ResultFormatter._format_room_recommendations(
                room_sections, selected_sections, selected_weekdays, max_rooms=5
            )
        else:
            result += "没有空闲教室\n"

        return result

    @staticmethod
    def format_specific_room_result(analysis_result: Dict[str, Any],
                                  building_code: str,
                                  target_room: str,
                                  selected_weekdays: List[int],
                                  selected_sections: List[int]) -> str:
        """
        格式化特定教室查询结果

        Args:
            analysis_result: 分析结果
            building_code: 教学楼代码
            target_room: 目标教室
            selected_weekdays: 选择的星期
            selected_sections: 选择的节次

        Returns:
            格式化的结果字符串
        """
        building_name = BuildingMapper.get_building_name(building_code)
        target_room_info = analysis_result['target_room_info']
        all_rooms = analysis_result['all_rooms']

        if target_room_info:
            # 找到了教室信息
            room_display = target_room_info[0]['room']  # 获取完整的教室名称（包含容量）
            result = f"{room_display} ({building_name})\n\n"

            # 按节次排序显示占用情况
            target_room_info.sort(key=lambda x: (x['section'], x['day']))

            # 获取该教室的所有占用信息
            occupied_sections = {}
            for room_info in target_room_info:
                if not room_info['is_free']:  # 只处理占用的时段
                    section = room_info['section']
                    day = room_info['day']
                    if section not in occupied_sections:
                        occupied_sections[section] = []
                    occupied_sections[section].append(day)

            # 显示占用的节次
            if occupied_sections:
                result += f"占用时间:\n"
                for section in sorted(occupied_sections.keys()):
                    days = sorted(occupied_sections[section])
                    weekday_map = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "日"}
                    if len(days) == 1:
                        result += f"  第{section}节: 星期{weekday_map[days[0]]}\n"
                    else:
                        days_str = "、".join([f"星期{weekday_map[d]}" for d in days])
                        result += f"  第{section}节: {days_str}\n"

            # 显示空闲时间段（基于查询的时间段计算）
            occupied_section_set = set(r['section'] for r in target_room_info if not r['is_free'])
            selected_section_set = set(selected_sections)
            free_sections = sorted(selected_section_set - occupied_section_set)

            if free_sections:
                result += f"\n空闲时间:\n"
                for section in free_sections:
                    result += f"  第{section}节: 完全空闲\n"

                # 如果有连续空闲时间段，特别标注
                if len(free_sections) > 1:
                    result += ResultFormatter._format_continuous_time(free_sections)
            else:
                result += f"\n查询时间段内暂无空闲时间\n"

        else:
            # 未找到教室
            result = f"未找到教室 {target_room}\n"

        return result

    @staticmethod
    def format_cache_based_result(target_room: str,
                                building_code: str,
                                selected_weekdays: List[int],
                                selected_sections: List[int]) -> str:
        """
        格式化基于缓存的结果

        Args:
            target_room: 目标教室
            building_code: 教学楼代码
            selected_weekdays: 选择的星期
            selected_sections: 选择的节次

        Returns:
            格式化的结果字符串
        """
        building_name = BuildingMapper.get_building_name(building_code)
        result = f"**{target_room} 查询结果** ({building_name})\n\n"
        result += f"*此结果基于缓存数据生成，实际状态请以最新查询为准*"
        return result

    @staticmethod
    def _format_time_range(selected_weekdays: List[int], selected_sections: List[int]) -> str:
        """格式化时间范围"""
        return ""

    @staticmethod
    def _format_room_recommendations(room_sections: Dict[str, set],
                                   selected_sections: List[int],
                                   selected_weekdays: List[int],
                                   max_rooms: int = 5) -> str:
        """格式化教室推荐"""
        # 找出真正的连续空闲时间段
        room_continuous_info = {}  # 教室 -> 最长连续时间段信息
        for room, sections in room_sections.items():
            sequences = RoomAnalyzer.find_continuous_sequences(sections)
            if sequences:
                longest_seq = max(sequences, key=len)
                room_continuous_info[room] = {
                    'length': len(longest_seq),
                    'sections': longest_seq,
                    'all_sections': sections
                }

        # 按最长连续时间排序
        rooms_by_continuous_time = sorted(
            room_continuous_info.items(),
            key=lambda x: x[1]['length'],  # 按连续空闲节次数量排序
            reverse=True
        )

        # 找出在所有查询节次都空闲的教室
        all_sections_free = []
        target_sections = set(selected_sections)
        for room, sections in room_sections.items():
            if sections == target_sections:
                all_sections_free.append(room)

        # 生成推荐结果
        result = f"\n推荐教室:\n"

        if all_sections_free:
            # 完全空闲的教室，按容量排序
            all_sections_free_with_capacity = [(room, RoomAnalyzer.extract_capacity(room)) for room in all_sections_free]
            all_sections_free_with_capacity.sort(key=lambda x: x[1])

            result += f"全时段空闲:\n"
            for room, capacity in all_sections_free_with_capacity[:max_rooms]:
                result += f"  {room}\n"
            if len(all_sections_free_with_capacity) > max_rooms:
                result += f"  ... 还有 {len(all_sections_free_with_capacity) - max_rooms} 个\n"

        # 只显示最长连续时间的教室，按容量排序
        max_continuous_length = 0
        if rooms_by_continuous_time:
            max_continuous_length = rooms_by_continuous_time[0][1]['length']

        longest_continuous_rooms = []
        for room, info in rooms_by_continuous_time:
            if info['length'] == max_continuous_length and room not in all_sections_free and info['length'] >= 2:
                longest_continuous_rooms.append((room, info['sections'], RoomAnalyzer.extract_capacity(room)))

        # 按容量从低到高排序
        longest_continuous_rooms.sort(key=lambda x: x[2])

        if longest_continuous_rooms and max_continuous_length >= 2:
            result += f"\n连续{max_continuous_length}节空闲:\n"
            for room, sections, capacity in longest_continuous_rooms[:max_rooms]:
                sections_str = ','.join(map(str, sections))
                result += f"  {room} - 第{sections_str}节\n"
            if len(longest_continuous_rooms) > max_rooms:
                result += f"  ... 还有 {len(longest_continuous_rooms) - max_rooms} 个\n"

        return result

    @staticmethod
    def _format_continuous_time(free_sections: List[int]) -> str:
        """格式化连续时间"""
        continuous_sequences = RoomAnalyzer.find_continuous_sequences(set(free_sections))

        result = f"\n🎯 **连续空闲时段**:\n"
        for seq in continuous_sequences:
            if len(seq) == 2:
                result += f"  第{seq[0]}-{seq[1]}节: 连续2节可用\n"
            else:
                result += f"  第{seq[0]}-{seq[-1]}节: 连续{len(seq)}节可用\n"

        return result

    @staticmethod
    def _extract_room_number(room_name: str):
        """从教室名称中提取房间号"""
        import re
        return re.search(r'(\d+)', room_name)